package lion.test.cms;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lion.framework.core.web.anno.Path;
import lion.framework.core.web.anno.Result;
import lion.framework.core.web.anno.View;
import lion.framework.core.web.request.Request;
import lion.framework.core.web.request.RequestMethod;
import lion.framework.core.web.views.ResultType;

public class ServiceA {

	@Path(value = "/blog/{id:int}/comment", method = RequestMethod.ALL)
	@Result({ @View(value = "/WEB-INF/web.xml"), @View(name = "error", value = "/blog/{id}/abc/{option}", type = ResultType.REDIRECT),
		@View(name = "aaa", type = ResultType.JSON) })
	public String blog(Request request) {

		System.out.println(request.toJSON());
		// DB db = SessionFactory.getCurrentDB("");

		// 1,返回view名称
		// 2,返回viewmodel
		// 3,不返回
		// request.addModel("time", new Date());
		System.out.println("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
		// 返回string 代表模版名称
		// 通过request 取值
		// 通过response设置值
		// 通过session设置session
		return "success";
	}

	@Path(value = "/async")
	public void asynch(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {

		System.out.println(request.getRequestURI());

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		File logFile = new File("c:/adminserver.log");
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(logFile), "GBK"));
			PrintWriter writer = response.getWriter();
			while (reader.ready()) {
				writer.write(escape(Thread.currentThread().getName() + "\t" + reader.readLine()));
				writer.flush();
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
	}

	private String escape(String message) {

		return "<script type='text/javascript'>\nwindow.parent.update(\"" + message.replaceAll("\n", "").replaceAll("\r", "")
				+ "\");</script>\n";
	}

}
